package com.jdrx.sw.sewage.common.util;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.MutablePropertyValues;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils extends org.springframework.beans.BeanUtils {
    public BeanUtils() {
    }

    public static Map<String, Object> populate(Object bean) {
        Map<String, Object> map = new HashMap();
        if (bean != null) {
            BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
            PropertyDescriptor[] descriptor = beanWrapper.getPropertyDescriptors();

            for(int i = 0; i < descriptor.length; ++i) {
                String name = descriptor[i].getName();
                if (!"class".equals(name)) {
                    map.put(name, beanWrapper.getPropertyValue(name));
                }
            }
        }

        return map;
    }

    public static <T> T copyProperties(Class<T> type, Object source) {
        T obj = instantiateClass(type);
        copyProperties((Object)source, (Object)obj);
        return obj;
    }

    public static <T> T copyProperties(Class<T> type, Map<String, Object> map) {
        T obj = instantiateClass(type);
        BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
        beanWrapper.setPropertyValues(new MutablePropertyValues(map), true, true);
        return obj;
    }
}
